package com.Tokiu.web;

import com.Tokiu.web.Util.sqlsessionfactoryDemo;
import com.Tokiu.web.mapper.userMapper;
import com.Tokiu.web.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //首先解决中文乱码问题
        request.setCharacterEncoding("UTF-8");

        //1.获取表单信息
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //2.定义User
        User u=new User();
        u.setUsername(username);
        u.setPassword(password);
        u.setGender("男");
        u.setAddr("西安财经大学");

        //3.调用mybatis
        //3.1 获取sqlsessionfactory对象

//        String resource = "mybatis-config.xml";
//        InputStream inputStream = Resources.getResourceAsStream(resource);
//        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //调用封装的sqlsessionFactory对象
        SqlSessionFactory sqlSessionFactory = sqlsessionfactoryDemo.Getsqlsessionfactory();
        //3.2 获取sqlsession对象

        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.3获取mapper

        userMapper mapper = sqlSession.getMapper(userMapper.class);

        User user = mapper.selectByUsername(username);

        response.setContentType("text/html;charset=utf-8");
        if(user==null)
        {
            //说明用户不存在
            mapper.addUser(u);
            //事务提交
            sqlSession.commit();
            response.getWriter().write("<h1>用户添加成功！</h1>");
            //释放资源
            sqlSession.close();
        }else {

            response.getWriter().write("<h1>用户已存在</h1>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
